<?php
        class model{ 
         private $db;
         public $arrayfileadmin=array("portalshelf","createshelf","editshelf","document","statadmin","usersettingdata");
         public $arrayfileuser=array("forgotpassword","login","resetpassword","checkmail"); 
        public $memcache;
         function setdb($db)
         {
             $this->db=$db;
         }
         function checkpermission($file,$type)
         {
           
            if(($_COOKIE['oauth'])&&$type==1) 
            {
             
              
              
              return true;
             
            
            }
            else if(($_COOKIE['oauth'])&&$type==2) 
            {
              if(in_array($file,$this->arrayfileadmin))
              {
              
              
              return true;
              }else
              {
              return false;
              }
            
            }
            else if(($_COOKIE['oauth'])&&$type==3) 
            {
              if(!in_array($file,$this->arrayfileadmin))
              {
              
              
              return true;
              }else
              {
              return false;
              }
            
            }
            else if(($_COOKIE['oauth'])&&$type==4) 
            {
              if(in_array($file,$this->arrayfileuser))
              {
              
              
              return true;
              }else
              {
              return false;
              }
            
            }
            else
            {
            
              return false;
            
            }
            
         
         
         }
         function checkresetpassword($forgotpassword)
         {
         $sql=" SELECT `tb_user`.userid FROM `tb_user` where `tb_user`.forgetcode='$forgotpassword'";
         $arrayuser=$this->db->db_set_recordset($sql);
         if($arrayuser[0]['userid'])
         {
         
         return true;
         }else
         {
         
         return false;
         } 
         
         }
         function checkadmin()
         {
            if($_COOKIE['oauth'])
            
            {
            
            $sql=" SELECT `tb_user`.status FROM `tb_user` where  `tb_user`.oauth ='".$_COOKIE['oauth']."' and  `tb_user`.status=2";
            

          $arrayuser=$this->db->db_set_recordset($sql);
           
           
           if($arrayuser[0]['status'])
           {
             
            return true;
           

           }else
           {
             return false;
           }
            }else
            {
             return false; 
            
            } 

         
         }
         function checkadminbyoauth($oauth)
         {
          if($oauth)
            
            {
            
            $sql=" SELECT `tb_user`.status FROM `tb_user` where  `tb_user`.oauth ='".$oauth."' and  `tb_user`.status=2";
            

          $arrayuser=$this->db->db_set_recordset($sql);
           
           
           if($arrayuser[0]['status'])
           {
             
            return true;
           

           }else
           {
             return false;
           }
            }else
            {
             return false; 
            
            } 
         
         }
         function logdata($userid,$tid)
         {
              $arraydata['userid']=$userid;
              $arraydata['tid']=$tid;
              $arraydata['ip']=$_SERVER['REMOTE_ADDR'];
              $arraydata['createdate']=date("Y-m-d H:i:s");
              $this->db->db_set($arraydata,"tb_log");
         }
         function logdatamobile($uuid,$tid,$description,$shelfid="",$bookid="")
         {
              $arraydata['uuid']=$uuid;
              $arraydata['tid']=$tid;
              $arraydata['description']=$description;
              if($shelfid)$arraydata['shelfid']=$shelfid;
              if($bookid)$arraydata['bookid']=$bookid;
              $arraydata['agent']=$_SERVER['HTTP_USER_AGENT'];
              $arraydata['ip']=$_SERVER['REMOTE_ADDR'];
              $arraydata['createdate']=date("Y-m-d H:i:s");
              $this->db->db_set($arraydata,"tb_log_mobile");
         }
         function getversion($shelfid)
         {
         $sql="SELECT
                    tb_version.version
                    FROM
                    tb_version
                    where tb_version.shelfid=".$shelfid;
         $arrayversion=$this->db->db_set_recordset($sql);  
         if($arrayversion[0]['version']) 
         {
         return $arrayversion[0]['version'];
         
         }else
         {
         return false;
         }        
         
         }
         function checktoken($token,$shelfid)
         {
         $sql="SELECT
            tb_token.`tokenid`
            FROM
            tb_token
            where tb_token.token='$token' and  tb_token.shelfid='$shelfid'
            ";
            $arraytoken=$this->db->db_set_recordset($sql);
            if($arraytoken[0]['tokenid'])
            {
            return true;
            }else
            {
            return false;
            }
         }
         function checkreadbook($bookid,$shelfid,$uuid)
         {
         $sql="SELECT
            tb_read.`readid`
            FROM
            tb_read
            where tb_read.uuid='$uuid' and tb_read.shelfid=$shelfid and  tb_read.bookid=$bookid
            ";
           // echo $sql;
            $arrayread=$this->db->db_set_recordset($sql);
            if($arrayread[0]['readid'])
            {
            return true;
            }else
            {
            return false;
            }
         }
         function checkdownloadbook($bookid,$shelfid,$uuid)
         {
         $sql="SELECT
            tb_download.`downid`
            FROM
            tb_download
            where tb_download.uuid='$uuid' and tb_download.shelfid=$shelfid and  tb_download.bookid=$bookid
            ";
           // echo $sql;
            $arrayread=$this->db->db_set_recordset($sql);
            if($arrayread[0]['downid'])
            {
            return true;
            }else
            {
            return false;
            }
         }
         function getuserbyoauth($oauth)
         {
            $sql=" SELECT
tb_user.shelfid,
tb_user.username,
tb_user.firstname,
tb_user.email,
tb_user.roleid,
tb_user.photo,
tb_user.userid
FROM
tb_user where  `tb_user`.oauth ='".$oauth."'  ";
            $arrayuser=$this->db->db_set_recordset($sql);
            if($this->checkadmin()&&$_GET['shelfid'])
            {
             $arrayuser[0]['shelfid'] =$_GET['shelfid'];
            
            }
            
            
            return   $arrayuser[0];
         
         }
         
         function getuserbyuserid($userid)
         {
            $sql=" SELECT
tb_user.shelfid,
tb_user.username,
tb_user.email,
tb_user.roleid,
tb_user.photo,
tb_user.userid
FROM
tb_user where  `tb_user`.userid ='".$userid."'  ";
            $arrayuser=$this->db->db_set_recordset($sql);
            if($this->checkadmin()&&$_GET['shelfid'])
            {
             $arrayuser[0]['shelfid'] =$_GET['shelfid'];
            
            }
            
            
            return   $arrayuser[0];
         
         }
         function getuserlistbyshelfid($shelfid)
         {
             $sql="SELECT
                        tb_user.userid,tb_user.email,tb_user.username
                        FROM
                        tb_user
                        where tb_user.shelfid=".$shelfid;
                        //echo   $sql;
                        
                        
            $arrayuserlist=$this->db->db_set_recordset($sql);
            return   $arrayuserlist;
         
         }
         function getshelfbyshelfid($shelfid)
         {
            $sql="SELECT
                        tb_shelf.*
                        FROM
                        tb_shelf
                        where tb_shelf.shelfid=".$shelfid;
                        
            $arrayshelf=$this->db->db_set_recordset($sql);
            return   $arrayshelf[0];
         
         
         }
         function getsortlist($shelfid)
         {
         
           $sql="select * from tb_sort where shelfid=".$shelfid;
           $arraysort=$this->db->db_set_recordset($sql);
           return   $arraysort;
         
         }
         function gettokenbyshelfid($shelfid)
         {
          $sql="SELECT * FROM `tb_token`
                        where tb_token.shelfid=".$shelfid;
                        
            $arraytoken=$this->db->db_set_recordset($sql);
            return   $arraytoken;
         
         
         }
         
           function gettokenbyuserids($userid)
         {
          $sql="  SELECT tb_token.* FROM tb_token
                     INNER JOIN tb_user ON tb_user.uuid=tb_token.uuid 
                     where tb_user.userid IN (".join(",",$userid).") ";
        
                        
            $arraytoken=$this->db->db_set_recordset($sql);
            return   $arraytoken;
         
         
         }
         
         
         
         
         function getdatabasebyshelfid($shelfid)
         {
         require_once(rootpath.'/library/database/phpMyDumper.php'); // uri
         $sql="select bookid from tb_book where shelfid=".$shelfid;
         $arraybook=$this->db->db_set_recordset($sql);
         $arraybook2=array();
         if(count($arraybook))
         {
         
         foreach($arraybook as $valuebook)
         {
         $arraybook2[]=$valuebook['bookid'];
         
         }
         }
         
         $connection=$this->db->getlink();
         $filename=dbpath.'/'.$shelfid.'-'.date("Y-m-d").'.sql';
         //echo $filename;
         $compress  = false; 
         $dump = new phpMyDumper(db_name,$connection,$filename,$compress);
         
         $dump->dropTable = true; // Dump DROP TABLE statement, default: true
         $dump->createTable = true; // Dump CREATE TABLE statement, default: true
         $dump->tableData = true; // Dump table data, default: true
         $dump->expInsert = false; // Dump expanded INSERT statements, default: false
         $dump->hexValue = false; // Dump strings as hex values, default: false
         $dump->phpMyAdmin = true; // Formats dump file like phpMyAdmin export, default: true
         $dump->utf8 = true; // Uses UTF-8 connection with MySQL server, default: true
         $dump->autoincrement = true; // Dump AUTO_INCREMENT statement using older MySQL servers, default: false
         $dump->wherenodata=array("tb_log","tb_log_mobile","tb_log_mobile","info_doc","info_parem","info_title");
         
         $whereshelfid=" where shelfid=".$shelfid;
         $wherebookid="";
         if(count($arraybook2))
         {
         $wherebookid=" where bookid IN (".join(",",$arraybook2)." ) "; 
         }
         
         $dump->whereselectdata['tb_banner']=$whereshelfid;
         $dump->whereselectdata['tb_banner_library']=$whereshelfid;
         $dump->whereselectdata['tb_boardcasting']=$whereshelfid;
         $dump->whereselectdata['tb_book']=$whereshelfid;
         $dump->whereselectdata['tb_cat']=$whereshelfid;
         if($wherebookid){ $dump->whereselectdata['tb_cat_relate']=$wherebookid;   }
         else { $dump->wherenodata[]='tb_cat_relate'; }
         $dump->whereselectdata['tb_del_book']=$whereshelfid;
         $dump->whereselectdata['tb_download']=$whereshelfid;
         if($wherebookid){ $dump->whereselectdata['tb_file']=$wherebookid;   }
         else { $dump->wherenodata[]='tb_file'; }
         if($wherebookid){ $dump->whereselectdata['tb_read']=$wherebookid;   }
         else { $dump->wherenodata[]='tb_read'; }
         if($wherebookid){ $dump->whereselectdata['tb_screenshot']=$wherebookid;   }
         else { $dump->wherenodata[]='tb_screenshot'; }
         $dump->whereselectdata['tb_shelf']=$whereshelfid;
         $dump->whereselectdata['tb_statdown']=$whereshelfid;
         $dump->whereselectdata['tb_statview']=$whereshelfid;
         $dump->whereselectdata['tb_tag']=$whereshelfid;
         if($wherebookid){ $dump->whereselectdata['tb_tag_relate']=$wherebookid;   }
         else { $dump->wherenodata[]='tb_tag_relate'; }
         $dump->whereselectdata['tb_user']=$whereshelfid." or shelfid=0";
         $dump->whereselectdata['tb_version']=$whereshelfid;
         
         
         
         
         
         
        
         $dump->doDump();
         
         
         }
         function getstatbyuserid($userid="",$sort,$startdate,$enddate,$shelfid="")
         {
           
          $where=array();
          switch ($sort) {
            case 1:
                $where[]="  (tb_download.createdate BETWEEN '".date("Y-m-d H:i:s",strtotime("-1 day"))."' AND '' '".date("Y-m-d H:i:s")."') ";
                //echo "i equals 0";
                break;
            case 2:
                $where[]="  (tb_download.createdate BETWEEN '".date("Y-m-d H:i:s",strtotime("-1 month"))."' AND '' '".date("Y-m-d H:i:s")."') ";
             //   echo "i equals 1";
                break;
            case 3:
                $where[]="   (tb_download.createdate BETWEEN '".date("Y-m-d H:i:s",strtotime("-1 year"))."' AND '".date("Y-m-d H:i:s")."') ";
               // echo "i equals 2";
                break;
             case 4:
                list($d1,$m1,$y1)=explode("/",$startdate);
                list($d2,$m2,$y2)=explode("/",$enddate);
                $where[]="  (tb_download.createdate BETWEEN '".($y1.'-'.$m1.'-'.$d1.' 00:00:00')."' AND '".($y2.'-'.$m2.'-'.$d2.' 23:59:59')."') ";
               // echo "i equals 2";
                break;
           }
          if($userid)
          {
          
           $where[]=" tb_book.createby=$userid ";
          
          }
          
           if($shelfid)
          {
          
           $where[]=" tb_book.shelfid=$shelfid ";
          
          }
          
          if(count($where))
          {
          $where=" where ".join(" and ",$where);
          
          }else
          {
          $where="";
          }
          
          $sql="SELECT
                        tb_book.title,
                        tb_book.bookid,
                        count(tb_download.downid) as countdownload
                        FROM
                        tb_book
                        LEFT JOIN tb_download ON tb_book.bookid = tb_download.bookid
                          
                        $where
                        GROUP BY bookid ";
         /// echo $sql;
          
         $arraybook=$this->db->db_set_recordset($sql);
         return   $arraybook;
         
         }
         
         function getstatbydate($day,$month,$year,$yearstart,$shelfid="",$userid="")
         {
           
          $where=array();
          $wherenotin=array();
          $arraynewdata=array();
          if($day&&$month&&$year)
          {
           $sort=1;
          }else if($month&&$year)
          {
           $sort=2;
          
          } else if($year)
          {
           $sort=3;
          
          }else if($yearstart)
          {
           $sort=4;
          
          }else
          {
          
          return false;
          } 
          
                                      //       sprintf("%04d-%02d-01 00:00:00", $year, $month, $day)
                                                                                                          
          switch ($sort) {
            case 1:
                $where[]="  (tb_download.createdate BETWEEN '".sprintf("%04d-%02d-%02d 00:00:00", $year, $month, $day)."' AND '".sprintf("%04d-%02d-%02d 23:59:59", $year, $month, $day)."' ) ";
                //echo "i equals 0";
                break;
            case 2:
                $d = new DateTime( sprintf("%04d-%02d-01 00:00:00", $year, $month, $day) );
                $t=$d->format( 't' );
                
                $where[]="  (tb_download.createdate BETWEEN '".sprintf("%04d-%02d-01 00:00:00", $year, $month)."' AND '".sprintf("%04d-%02d-".$t." 23:59:59", $year, $month)."' ) ";
             //   echo "i equals 1";
                break;
            case 3:
                $where[]="   (tb_download.createdate BETWEEN '".sprintf("%04d-01-01 00:00:00", $year)."' AND '".sprintf("%04d-12-31 23:59:59", $year)."'  ) ";
               // echo "i equals 2";
                break;
            case 4:
                $where[]="   (tb_download.createdate BETWEEN '".sprintf("%04d-01-01 00:00:00", $yearstart)."' AND '".sprintf("%04d-12-31 23:59:59", date('Y'))."'  ) ";
               // echo "i equals 2";
                break;
             case 5:
                list($d1,$m1,$y1)=explode("/",$startdate);
                list($d2,$m2,$y2)=explode("/",$enddate);
                $where[]="  (tb_download.createdate BETWEEN '".($y1.'-'.$m1.'-'.$d1.' 00:00:00')."' AND '".($y2.'-'.$m2.'-'.$d2.' 23:59:59')."') ";
               // echo "i equals 2";
                break;
           }
          if($userid)
          {
          
           $where[]=" tb_book.createby=$userid ";
           
           
          
          }
          
           if($shelfid)
          {
          
           $where[]=" tb_book.shelfid=$shelfid ";
           $wherenotin[]=" tb_book.shelfid=$shelfid ";
          
          }
          
          if(count($where))
          {
          $where=" where ".join(" and ",$where);
          
          }else
          {
          $where="";
          }
          
          
          if(count($wherenotin))
          {
          $wherenotin=" where ".join(" and ",$wherenotin);
          
          }else
          {
          $wherenotin="";
          }
          
          $sql="SELECT
                        tb_book.title,
                        tb_book.bookid,
                        tb_book.shelfid,
                        tb_download.downid, 
                        tb_download.createdate
                        FROM
                        tb_book
                        LEFT JOIN tb_download ON tb_book.bookid = tb_download.bookid
                          
                        $where
                        order by tb_download.createdate asc
                        
                         ";
         //echo $sql;
          
         $arraybook=$this->db->db_set_recordset($sql);
         
         
         
         
         
         $sql="      SELECT
                        tb_book.title,
                        tb_book.bookid,
                        tb_book.shelfid
                        FROM
                        tb_book
                          
                        $wherenotin
                        
                         ";
         /// echo $sql;
          
         $arrayallbook=$this->db->db_set_recordset($sql);
         
         $arraynewdata[0]=$arraybook;
         $arraynewdata[1]=$arrayallbook; 
         
         
         return   $arraynewdata;
         
         }
         
         function getbannerbyshelfid($shelfid)
         {
            $sql="SELECT
                      tb_banner.bannerid,
                      tb_banner.shelfid,
                      tb_banner.link,
                      tb_banner.photo,
                      
                      tb_banner.sort,
                      tb_banner.createdate
                      FROM
                      tb_banner
                      where tb_banner.shelfid=".$shelfid;
                        
            $arraybanner=$this->db->db_set_recordset($sql);
            
            if(count($arraybanner))
            {
            $k=0;
            foreach($arraybanner as $valuebanner)
            {
            
            if(strpos($arraybanner[$k]['link'],"http://")!==false )
            {
            
            $arraybanner[$k]['status']=1;
            
            } else
            {
          $arraybanner[$k]['status']=2;  
            
            }
              $k++;
            
            }
            
            }
            
            return   $arraybanner;
         
         
         }
         function getallbook($shelfid,$oauth="",$tagid="",$search="",$oauth2="",$orderby="")
         {
            $join="";
            $where[]=" tb_book.shelfid='".$shelfid."'  ";

             if($this->checkadminbyoauth($oauth))
            {

            }else if($oauth2)
            {
            $join.=" INNER JOIN tb_user_relate ON tb_book.bookid = tb_user_relate.bookid ";
            $join.=" INNER JOIN tb_user as tb_user2 ON tb_user_relate.userid = tb_user2.userid ";
            $where[]=" (tb_user2.oauth='".$oauth2."' or tb_user.oauth='".$oauth2."' ) ";
            $groupby=" group by tb_book.bookid ";
            
            
            }else if($oauth)
            {
            $join.=" INNER JOIN tb_user_relate ON tb_book.bookid = tb_user_relate.bookid ";
            $join.=" INNER JOIN tb_user as tb_user2 ON tb_user_relate.userid = tb_user2.userid ";
            $where[]=" (tb_user2.oauth='".$oauth."' or tb_user.oauth='".$oauth."')  ";
            $groupby=" group by tb_book.bookid ";
            
            
            }else
            {
            exit;
            
            }
            
            
            if($tagid)
            {
            $join.=" LEFT JOIN tb_tag_relate ON tb_book.bookid = tb_tag_relate.bookid ";
            $where[]=" tb_tag_relate.tagid='".$tagid."' ";
            $groupby=" group by tb_book.bookid ";
            
            
            }
            
            if($search)
            {
          //  $join.=" LEFT JOIN tb_tag_relate ON tb_book.bookid = tb_tag_relate.bookid ";
            $where[]=" tb_book.title like '%".$search."%' or tb_book.description like '%".$search."%' ";
          //  $groupby=" group by tb_book.bookid ";
            
            
            }
            
            if(count($where))
            {
            $where=' where '.join(" and ",$where);
            }
            
            $sql="
            SELECT
            tb_book.*,
            tb_user.oauth,
            tb_user.userid,
            tb_user.photo as avatarphoto,
            IF(tb_user.firstname = '', tb_user.username, tb_user.firstname) as username
            
            FROM
            tb_book
            INNER JOIN tb_user ON tb_book.createby = tb_user.userid
            $join
            $where
            $groupby
            $orderby
            ";
            
            //echo $sql;
//            exit;

            $arraybook=$this->db->db_set_recordset($sql);
           // $this->db->closedb(); 
            
            return      $arraybook;
              
           } 
         function getmoreappbyshelfid($shelfid)
         {
         $sql="SELECT
                    tb_moreapp.name,tb_moreapp.link,tb_moreapp.status
                    FROM
                    tb_moreapp
                    where tb_moreapp.shelfid=".$shelfid;
          $arraybooktype=$this->db->db_set_recordset($sql);
          return $arraybooktype;
         
         }
         function getbooktypebyshelfid($shelfid)
         {
         
          $sql="SELECT
tb_cat.catid,tb_cat.name
FROM
tb_cat
where tb_cat.shelfid=".$shelfid;
          $arraybooktype=$this->db->db_set_recordset($sql);
          return $arraybooktype;
         }
         function getbookbybookid($bookid,$swap=0,$uuid="")
         { 
            require_once(rootpath.'/library/plugins/general_pi.php'); // uri
            $arraydata=array();
         
            $sql="
            SELECT
            tb_book.*,
            DATE_FORMAT(tb_book.updatedate,'%M %d,%Y') updatedate2,
            DATE_FORMAT(tb_book.date,'%d/%m/%Y') datedata,
            IF (tb_user.oauth, tb_user.oauth,'0') as oauth,
            IF (tb_user.username IS NULL , 'No User',tb_user.username) as username
            FROM
            tb_book
            LEFT JOIN tb_user ON tb_book.createby = tb_user.userid
            where tb_book.bookid='".$bookid."' 
            ";

            
            $arraybook=$this->db->db_set_recordset($sql);
            
            if($this->checkadmin())
            {
             $arraybook['0']['admin']=1;
            
            }else
            {
             $arraybook['0']['admin']=0;
            
            }
            

            
            
            if($arraybook['0']['time'])
            {
            list($h1,$m1,$s1)=explode(":",$arraybook['0']['time']);
            list($h2,$m2,$s2)=explode(":",$arraybook['0']['time2']);
            $arraybook['0']['time1']=$arraybook['0']['time'];
            $arraybook['0']['time']=$h1.'.'.$m1.'-'.$h2.'.'.$m2.' น.';
            
            }
            
            
            
           if($swap==1)
           {
           if($arraybook[0]['photo'])
           {
           $arraybook[0]['photo']=imginfo.'/'.$arraybook[0]['shelfid'].'/'.$arraybook[0]['bookid'].'/'.$arraybook[0]['photo'];
           }else
           {
           $arraybook[0]['photo']=baseinfo.'/img/topic.png';
           }
           
           
           
           if($uuid)
           {
           //echo "<pre>";
//           print_r($this->checkreadbook($arraybook[0]['bookid'],$arraybook[0]['shelfid'],$uuid));
//           echo "</pre>;";

           if($this->checkreadbook($arraybook[0]['bookid'],$arraybook[0]['shelfid'],$uuid))
           {
           $arraybook[0]['statuebook']="old";
           }else
           {
           $arraybook[0]['statuebook']="new";
           }
           }
           
          
           
           }
           
           $arraybook[0]['version']= $this->getversionbook($arraybook[0]['bookid']);
           
           $arraydata['book']=$arraybook[0];
           
           $sql="select tb_cat.catid,tb_cat.`name` FROM tb_cat_relate INNER JOIN tb_cat ON tb_cat.catid = tb_cat_relate.catid where tb_cat_relate.bookid=".$bookid;
           $arraycat=$this->db->db_set_recordset($sql);
           
           
           
           
           if($swap==0)
           {
           $arraydata['cat']=array();
           }else
           {
           $arraydata['book']['cat']=array();
           
           }
           
           $sql="SELECT
tb_user.`username`,tb_user.`userid`,tb_user.`email`
FROM
tb_user
INNER JOIN tb_user_relate ON tb_user.userid = tb_user_relate.userid
where tb_user_relate.bookid=".$bookid;
          $arrayuser=$this->db->db_set_recordset($sql);
          
           if($swap==0)
           {
           $arraydata['user']=array();
           }else
           {
           $arraydata['book']['user']=array();
           
           }

           
           if(count($arraycat))
           {
           $k=0;
           foreach($arraycat as $valuecat)
           {
           if($swap==0)
           {
           $arraydata['cat'][]=$valuecat['catid'];
           }else
           {
           $arraydata['book']['cat'][$k]['catid']=$valuecat['catid'];
           $arraydata['book']['cat'][$k]['name']=$valuecat['name'];
           }
           $k++;
           
           }
           
           }
           
           
            if(count($arrayuser))
           {
           $k=0;
           foreach($arrayuser as $valueuser)
           {
           if($swap==0)
           {
           $arraydata['user'][]=$valueuser['userid'];
           $arraydata['username'][]=$valueuser['username'];
           $arraydata['email'][]=$valueuser['email'];
           
           
           }else
           {
           $arraydata['book']['user'][$k]['userid']=$valueuser['userid'];
           $arraydata['book']['user'][$k]['username']=$valueuser['username'];
           $arraydata['book']['user'][$k]['email']=$valueuser['email'];
           
           }
           $k++;
           
           }
           
           }
           
           
           $sql="select tb_tag_relate.tagid,tb_tag.name FROM tb_tag_relate INNER JOIN tb_tag ON tb_tag.tagid = tb_tag_relate.tagid where tb_tag_relate.bookid=".$bookid;
           $arraycat=$this->db->db_set_recordset($sql);
            if($swap==0)
           {
           $arraydata['tag']=array();
           
           }else
           {
           $arraydata['book']['tag']=array();
           
           }
           //$arraydata['tag']=array();
           if(count($arraycat))
           {
           $k=0;
           foreach($arraycat as $valuecat)
           {
           if($swap==0)
           {
           $arraydata['tag'][]=$valuecat['tagid'];
           }else
           {
           $arraydata['book']['tag'][$k]['tagid']=$valuecat['tagid'];
           $arraydata['book']['tag'][$k]['name']=$valuecat['name'];
           }
           $k++;
           
           
           }
           
           }
           
           if($swap==1)
           {
           $sql="SELECT
                    tb_file.*,
                    tb_type_file.`name` as filetype
                    FROM
                    tb_file
                    
                    INNER JOIN tb_type_file ON tb_file.typeid = tb_type_file.typeid
                    where tb_file.bookid=".$bookid."
                    order by tb_file.name asc
                    ";
           //echo $sql;
           $arrayfile=$this->db->db_set_recordset($sql);
           $arraynewfile=array();
           $arrayfile2=array();
           if(count($arrayfile)&&$arrayfile)
           {
           $k=0;
           $row2=0; 
           $tempgroup=0;
           $tempgroup2=0;
           
           foreach($arrayfile as $valuefile)
           {

           $filesize=filesize(filepath.'/'.$arraybook[0]['shelfid'].'/'.$arraybook[0]['bookid'].'/'.$valuefile['file']);

          
           $arraydata['book']['filearr'][$k]['fileid']= $valuefile['fileid']; 
           $arraydata['book']['filearr'][$k]['name']= $valuefile['name'];
           
           
           
           
           $arraydata['book']['filearr'][$k]['file']= fileinfo.'/'.$arraybook[0]['shelfid'].'/'.$arraybook[0]['bookid'].'/'.$valuefile['file'];
           //$arraydata['book']['filearr'][$k]['file2']= $valuefile['file'];
           $arraydata['book']['filearr'][$k]['filesize']= number_format(($filesize/1000000), 2, '.', '').'MB';
           $arraydata['book']['filearr'][$k]['sort']= $valuefile['sort'];
           $arraydata['book']['filearr'][$k]['filetype']=strtoupper($valuefile['filetype']);  
           
           $arraydata['book']['filearr'][$k]['filetype2']= $valuefile['filetype'];
             
           $arraydata['book']['filearr'][$k]['typeid']=$valuefile['typeid'];   
           if($valuefile['img']&&$valuefile['img']!='meet.png') 
           {
           
                
           $arraydata['book']['filearr'][$k]['img']= imginfo.'/'.$arraybook[0]['shelfid'].'/'.$arraybook[0]['bookid'].'/banner/'.$valuefile['img'];
           
           //$arraydata['book']['filearr'][$k]['img2']= $valuefile['img'];
           }
           else
           {
           $arraydata['book']['filearr'][$k]['img']=baseinfo.'/img/meet.png';
           //$arraydata['book']['filearr'][$k]['img2']= "";
           }
           
           $arraydata['book']['filearr'][$k]['group']= $valuefile['group'];
           
           
           
           
           $k++;
          
            
           
           
           }
           
           }
           
           

           }else
           {
           $sql="SELECT
                    tb_type_file.`name` as filetype,
                    tb_type_file.typeid,
                    tb_file.*
                    FROM
                    tb_file
                    INNER JOIN tb_type_file ON tb_file.typeid = tb_type_file.typeid
                    where tb_file.bookid=".$bookid.' order by tb_file.name asc';
           $arrayfile=$this->db->db_set_recordset($sql);
           $arrayfile2=array();
           if(count($arrayfile))
           {
           $k=0;
           $row2=0; 
           $tempgroup=0;
           $tempgroup2=0;
           foreach($arrayfile as $valuefile)
           {

           $filesize=filesize(filepath.'/'.$arraybook[0]['shelfid'].'/'.$arraybook[0]['bookid'].'/'.$valuefile['file']);

          
           
           $arraydata['book']['filearr'][$k]['name']= $valuefile['name'];
           
           
           
           $arraydata['book']['filearr'][$k]['file']= fileinfo.'/'.$arraybook[0]['shelfid'].'/'.$arraybook[0]['bookid'].'/'.$valuefile['file'];
           $arraydata['book']['filearr'][$k]['file2']= $valuefile['file'];
           $arraydata['book']['filearr'][$k]['filesize']= number_format(($filesize/1000000), 2, '.', '').'MB';
           $arraydata['book']['filearr'][$k]['sort']= $valuefile['sort'];
           $arraydata['book']['filearr'][$k]['filetype']=strtoupper($valuefile['filetype']);  
           
           $arraydata['book']['filearr'][$k]['filetype2']= $valuefile['filetype'];
             
           $arraydata['book']['filearr'][$k]['typeid']=$valuefile['typeid'];   
           if($valuefile['img']&&$valuefile['img']!='meet.png') 
           {
           
                
           $arraydata['book']['filearr'][$k]['img']= imginfo.'/'.$arraybook[0]['shelfid'].'/'.$arraybook[0]['bookid'].'/banner/'.$valuefile['img'];
           
           $arraydata['book']['filearr'][$k]['img2']= $valuefile['img'];
           }else
           {
           $arraydata['book']['filearr'][$k]['img']=baseinfo.'/img/meet.png';;
           $arraydata['book']['filearr'][$k]['img2']= "meet.png";
           }
           
           $arraydata['book']['filearr'][$k]['group']= $valuefile['group'];
           
           
           
           
         $k++;
          
            
           
           
           }
           
           }
           
           
           $sql="SELECT
tb_cat.`name`
FROM
tb_cat
INNER JOIN tb_cat_relate ON tb_cat.catid = tb_cat_relate.catid
where tb_cat_relate.bookid=".$bookid;
          $arraybooktype=$this->db->db_set_recordset($sql);
          $arraybooktype2=array();
          if(count($arraybooktype))
          {
          foreach($arraybooktype as $booktype)
          {
          $arraybooktype2[]=$booktype['name'];
          }
          }
          $arraydata['book']['booktype']=join(",",$arraybooktype2);
          
          
          
         // $arraybooktype=$this->db->db_set_recordset($sql);
//          $arraybooktype2=array();
//          if(count($arraybooktype))
//          {
//          foreach($arraybooktype as $booktype)
//          {
//          $arraybooktype2[]=$booktype['username'];
//          }
//          }
          //$arraydata['book']['user']=join(",",$arraybooktype2);
          
          
          
          }
          
          
          
        
           
        
            
            
            return      $arraydata;
         
         }
         
          function pushnotification($arraydata,$pempath,$passphrase)
          {

           
        $gateway="gateway.push.apple.com:2195";    
              
        if(is_file($pempath))
        {
       // echo rootpathbasemain.'/pem/'.folderpath.'/'.$pem.'/'.$pem.'.pem'; 
            $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', $pempath);
            stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);


        $fp = stream_socket_client(
        'ssl://'.$gateway, $err,
        $errstr, 120, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

        if (!$fp)
        exit("" . PHP_EOL);
        $k=0;
        foreach($arraydata as $valuedata)
        {
        //$body['aps']=$valuedata;
        
        $body['aps']['alert']=$valuedata['alert'];
        $body['aps']['type']=$valuedata['type'];
        $body['aps']['badge']=$valuedata['badge'];
        
       
       // $body['aps'] = array(
//        'alert' => $message,
//        'type' => $type,
//        'sound' => 'default',
//        'badge' => $badge,
//        'mid'=> $mid
//        );
        
         //echo           $deviceToken;
    // Encode the payload as JSON
        $payload = json_encode($body);

    // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $valuedata['token']) . pack('n', strlen($payload)) . $payload;
    //    echo       $deviceToken."<br>";
    // Send it to the server
        if(@fwrite($fp, $msg, strlen($msg)))
        {
          // echo    "1==>".$deviceToken."<br>";
              // $result = fwrite($fp, $msg, strlen($msg)); 
        }else
        {
         //  echo    "2==>".$deviceToken."<br>";
           $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', $pempath);
            stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
            
           $fp = stream_socket_client(
        'ssl://'.$gateway, $err,
        $errstr, 120, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
        
        }
       
      
        
        $k++;
        }
       
        fclose($fp);
        }

          }
         
         function getversionbook($bookid)
         {
           $sql="
            SELECT
            tb_version_book.*
            FROM
            tb_version_book
            where tb_version_book.bookid='".$bookid."' 
            ";
            
            $arraybook=$this->db->db_set_recordset($sql);
            if($arraybook['0']['vid'])
            {
            return $arraybook['0']['version'];
            
            }else
            {
            
            $arraydata['bookid']=$bookid;
            $arraydata['version']=1;
            $this->db->db_set($arraydata,"tb_version_book");
            
            
            return "1";
            
            }
         
         }
         function setversionbook($bookid)
         {
         
            $version=$this->getversionbook($bookid);
            $arraydata['bookid']=$bookid;
            $arraydata['version']=$version+1;
            $this->db->db_set($arraydata,"tb_version_book"," bookid=".$bookid);
         
         }
         function getbannerlibrarybyshelfid($shelfid)
         {
            $sql="SELECT
                        tb_banner_library.bannerlid,
                        tb_banner_library.shelfid,
                        tb_banner_library.link,
                        tb_banner_library.photo,
                        tb_banner_library.sort,
                        tb_banner_library.createdate
                        FROM
                        tb_banner_library
                      where tb_banner_library.shelfid=".$shelfid;
                        
            $arraybanner=$this->db->db_set_recordset($sql);
            return   $arraybanner;
         
         
         }
         function getmytagbyuserid($userid)
         {
            $sql="SELECT
            tb_tag.`name`,
            tb_tag.`tagid`
            FROM
            tb_book
            INNER JOIN tb_tag_relate ON tb_book.bookid = tb_tag_relate.bookid
            INNER JOIN tb_tag ON tb_tag_relate.tagid = tb_tag.tagid
            where tb_book.createby=$userid
            GROUP BY tb_tag.`tagid`";
            $arraytag=$this->db->db_set_recordset($sql);
            return   $arraytag;
         
         }
         function getalltagbyshelfid($shelfid)
         {
         
             $sql="SELECT
            tb_tag.`name`,
            tb_tag.`tagid`
            FROM
            tb_tag
            where tb_tag.shelfid=$shelfid  order by tb_tag.`name` asc
            ";
            $arraytag=$this->db->db_set_recordset($sql);
            return   $arraytag;
         
         }
         function checktitleshelf($name)
         {
             if($name)
             {
             $sql="SELECT `tb_shelf`.shelfid FROM `tb_shelf` where tb_shelf.name='$name' ";
             $arrayuser=$this->db->db_set_recordset($sql);
             
             
               if($arrayuser[0]['shelfid'])
               {
                return true;
               }else
               {
                 return false;
               }
             
             }else
             {
             
             return false;
             }
         
         }
         function checkuser($shelfid="")
         {
          if($_COOKIE['oauth'])
          {
            $shelfwhere="";
            if($shelfid)
            {
            $shelfwhere=" and tb_user.shelfid=".$shelfid; 
            
            }
            
            $sql=" SELECT `tb_user`.userid FROM `tb_user` where  `tb_user`.oauth ='".$_COOKIE['oauth']."' ".$shelfwhere;
            $arrayuser=$this->db->db_set_recordset($sql);
           
           if($arrayuser[0]['userid'])
           {
            return true;
           }else
           {
             return false;
           }
           }else
           {
             return false;
           
           }
         
         }
         function checkuserbyusername($username)
         {
           if($username)
          {
            $sql=" SELECT `tb_user`.userid FROM `tb_user` where  `tb_user`.username ='".$username."'  ";
            $arrayuser=$this->db->db_set_recordset($sql);
           if($arrayuser[0]['userid'])
           {
            return true;
           }else
           {
             return false;
           }
           }else
           {
             return false;
           
           }
         
         }        
         function checkcatbycatname($catname,$shelfid)
         {
            if($catname)
          {
            $sql=" SELECT `tb_cat`.catid FROM `tb_cat` where  `tb_cat`.name ='".$catname."' and    `tb_cat`.shelfid=$shelfid  ";
            $arraycat=$this->db->db_set_recordset($sql);
           if($arraycat[0]['catid'])
           {
            return true;
           }else
           {
             return false;
           }
           }else
           {
             return false;
           
           }
         
         }         
         function checktagbytagname($tagname,$shelfid)
         {
          if($tagname)
          {
            $sql=" SELECT `tb_tag`.tagid FROM `tb_tag` where  `tb_tag`.name ='".$tagname."' and    `tb_tag`.shelfid=$shelfid  ";
            $arraytag=$this->db->db_set_recordset($sql);
           if($arraytag[0]['tagid'])
           {
            return true;
           }else
           {
             return false;
           }
           }else
           {
             return false;
           
           }
         
         }       
         function checkuserbyemail($email)
         {
           if($email)
          {
            $sql=" SELECT `tb_user`.userid FROM `tb_user` where  `tb_user`.email ='".$email."'  ";
            $arrayuser=$this->db->db_set_recordset($sql);
           if($arrayuser[0]['userid'])
           {
            return true;
           }else
           {
             return false;
           }
           }else
           {
             return false;
           
           }
         
         }
         
         function setuuidbyuserid($uuid,$userid)
         {
         $arrayhello=array();
         $arrayhello['uuid']="";
         $this->db->db_set($arrayhello,"tb_user"," uuid='".$uuid."'");  
                
                
         $arrayhello=array();
         $arrayhello['uuid']=$uuid;
         $this->db->db_set($arrayhello,"tb_user"," userid='".$userid."'"); 
         
         }
         
         
        
        }
?>
